package com.study.spring.thread;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * TODO
 *
 * @author: zhang
 * @version: 3.0
 * @date: 2019-09-01 15:42:03
 * @since 1.8
 **/
public class TestLock {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestLock.class);
    private int total = 3;
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public static void main(String[] args) {
        TestLock testLock = new TestLock();
        //noinspection AlibabaAvoidManuallyCreateThread
        new Thread(new Runnable() {
            @Override
            public void run() {
                testLock.get();
                LOGGER.info(1 + "");
            }
        }, "1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                testLock.get();
            }
        }, "2").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                testLock.get();
            }
        }, "3").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                testLock.get();
            }
        }, "4").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                testLock.get();
            }
        }, "5").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                testLock.get();
            }
        }, "6").start();

        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                testLock.returnObj();
            }
        }, "7").start();
    }

    public void get() {
        try {
            lock.lock();
            if (total > 0) {
                total--;
            } else {
                condition.await();
            }
        } catch (InterruptedException e) {
        } finally {
            lock.unlock();
        }
    }

    public void returnObj() {
        try {
            lock.lock();
            total++;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
